package hhtc.jsjds.utils;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.*;
import java.io.*;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Iterator;
import java.util.List;
import java.util.Map;


public class HttpRequest {
    protected static Logger logger = LoggerFactory.getLogger(HttpRequest.class);

    public HttpRequest() {
    }

    public static String sendPost(String requestUrl, String outputStr) {
        return requestUrl.toLowerCase().startsWith("https") ? sendHttpsPost(requestUrl, outputStr, (Map) null) : sendHttpPost(requestUrl, outputStr, (Map) null);
    }

    public static String sendPost(String requestUrl, String outputStr, Map<String, String> heads) {
        return requestUrl.toLowerCase().startsWith("https") ? sendHttpsPost(requestUrl, outputStr, heads) : sendHttpPost(requestUrl, outputStr, heads);
    }

    public static String sendGet(String url, String param) {
        String result = "";
        BufferedReader in = null;

        try {
            String urlNameString = url;
            if (StringUtils.isNotBlank(param)) {
                urlNameString = url + "?" + param;
            }

            System.out.println(urlNameString);
            URL realUrl = new URL(urlNameString);
            URLConnection connection = realUrl.openConnection();
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            connection.connect();
            Map<String, List<String>> map = connection.getHeaderFields();

            String line;
            for (in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8")); (line = in.readLine()) != null; result = result + line) {
            }
        } catch (Exception var17) {
            System.out.println("发送GET请求出现异常！" + var17);
            var17.printStackTrace();
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception var16) {
                var16.printStackTrace();
            }

        }

        return result;
    }

    public static String sendHttpPost(String url, String param, Map<String, String> heads) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";

        try {
            URL realUrl = new URL(url);
            URLConnection conn = realUrl.openConnection();
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            conn.setRequestProperty("Accept-Charset", "UTF-8");
            conn.setRequestProperty("contentType", "UTF-8");
            String line;
            if (null != heads) {
                Iterator var8 = heads.keySet().iterator();

                while (var8.hasNext()) {
                    line = (String) var8.next();
                    conn.setRequestProperty(line, (String) heads.get(line));
                }
            }

            conn.setDoOutput(true);
            conn.setDoInput(true);
            OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream(), "utf-8");
            out = new PrintWriter(writer);
            out.print(param);
            out.flush();

            for (in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8")); (line = in.readLine()) != null; result = result + line) {
            }
        } catch (Exception var18) {
            System.out.println("发送 POST 请求出现异常！" + var18);
            var18.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }

                if (in != null) {
                    in.close();
                }
            } catch (IOException var17) {
                var17.printStackTrace();
            }

        }

        return result;
    }

    public static String sendPostJson(String url, String Params) throws IOException {
        OutputStreamWriter out = null;
        BufferedReader reader = null;
        String response = "";

        try {
            URL httpUrl = null;
            httpUrl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) httpUrl.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("connection", "keep-alive");
            conn.setUseCaches(false);
            conn.setInstanceFollowRedirects(true);
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.connect();
            out = new OutputStreamWriter(conn.getOutputStream());
            out.write(Params);
            out.flush();

            String lines;
            for (reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); (lines = reader.readLine()) != null; response = response + lines) {
                lines = new String(lines.getBytes(), "utf-8");
            }

            reader.close();
            conn.disconnect();
        } catch (Exception var16) {
            System.out.println("发送 POST 请求出现异常！" + var16);
            var16.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }

                if (reader != null) {
                    reader.close();
                }
            } catch (IOException var15) {
                var15.printStackTrace();
            }

        }

        return response;
    }

    public static String sendHttpsPost(String requestUrl, String outputStr, Map<String, String> heads) {
        JSONObject jsonObject = null;
        StringBuffer buffer = new StringBuffer();

        try {
            TrustManager[] tm = new TrustManager[]{new X509TrustManager() {
                @Override
                public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
                }

                @Override
                public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
                }

                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    return new X509Certificate[0];
                }
            }};
            SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
            sslContext.init((KeyManager[]) null, tm, new SecureRandom());
            SSLSocketFactory ssf = sslContext.getSocketFactory();
            URL url = new URL(requestUrl);
            HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
            httpUrlConn.setSSLSocketFactory(ssf);
            httpUrlConn.setDoOutput(true);
            httpUrlConn.setDoInput(true);
            httpUrlConn.setUseCaches(false);
            httpUrlConn.setRequestMethod("POST");
            if (null != heads) {
                Iterator inputStream = heads.keySet().iterator();

                while (inputStream.hasNext()) {
                    String key = (String) inputStream.next();
                    httpUrlConn.setRequestProperty(key, (String) heads.get(key));
                }
            }

            httpUrlConn.connect();
            if (null != outputStr) {
                OutputStream outputStream = httpUrlConn.getOutputStream();
                outputStream.write(outputStr.getBytes("UTF-8"));
                outputStream.flush();
                outputStream.close();
            }

            InputStream inputStream = httpUrlConn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String str = null;

            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }

            bufferedReader.close();
            inputStreamReader.close();
            inputStream.close();
            inputStream = null;
            httpUrlConn.disconnect();
            jsonObject = JSONObject.parseObject(buffer.toString());
        } catch (ConnectException var14) {
            logger.error("server connection timed out.");
        } catch (Exception var15) {
            logger.error("https request error:{}", var15);
        }

        return buffer.toString();
    }
}
